package com.hzjq.core.impl

import com.hzjq.core.bean.CapProgressEntity
import com.hzjq.core.bean.ErrorResult
import com.hzjq.core.callback.Checker
import com.hzjq.core.callback.ProgressCallback
import com.hzjq.core.serial.SerialManager
import com.hzjq.core.worker.ElectricVoltageWork
import io.reactivex.functions.Consumer

class CheckerImpl : Checker {

    private var mElectricVoltageWork: ElectricVoltageWork? = null

    private var callback: Consumer<Boolean>? = null

    override fun start() {
        stop()
        mElectricVoltageWork = ElectricVoltageWork(object : ProgressCallback<CapProgressEntity> {
            override fun onResult(t: CapProgressEntity) {
                stop()
                if(t.stateCode == 104){
                    callback?.accept(false)
                } else {
                    callback?.accept(true)
                }
            }

            override fun onRetryCountChanged(retryCount: Int, action: String) {
                if(retryCount == 3) {
                    SerialManager.getInstance().enablePio(true)
                } else if(retryCount == 7){
                    stop()
                    callback?.accept(false)
                }
            }

            override fun onError(errorCode: ErrorResult) {
                stop()
                callback?.accept(false)
            }

            override fun onProgressChanged(progress: Int, total: Int, action: String) {

            }

        })
        mElectricVoltageWork?.isStop(false)
        mElectricVoltageWork?.doWork()
    }


    fun setCallback(callback: Consumer<Boolean>):CheckerImpl{
        this.callback = callback
        return this
    }

    override fun stop() {
        mElectricVoltageWork?.isStop(true)
        mElectricVoltageWork?.cancel()
    }
}